package Products;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.joda.time.DateTime;

import Exceptions.HistoricalInformationException;
import Magnitudes.Money;

public class HistoricalMapDateMoney {

	private Map<Date, Money> historicalRecord;
	
	
	public HistoricalMapDateMoney(){
		this.historicalRecord = new TreeMap<Date, Money>();
	}
	
		
	
	
	public Map<Date, Money> getHistoricalRecord(){
		return this.historicalRecord;
	}
	
	
	
	public Money priceAt(DateTime dateTime) throws HistoricalInformationException {
		
		Date keyToFind = this.obtainBestKey(dateTime);
		if (keyToFind == null){
			throw new HistoricalInformationException();
		}
		@SuppressWarnings("deprecation")
		Money money = this.getHistoricalRecord().get((new DateTime(keyToFind).toDateMidnight().toDate()));
		return money;			
	}



	private Date obtainBestKey(DateTime dateTime) {
		Set<Date> keys = this.getHistoricalRecord().keySet();
		Date given = dateTime.toDate();
		Date closest = null;
		int i = 0;
		for (Date key: keys){
			if (key.before(given) && i == 0) {
				closest = key;
				i++;
			}
			if (key.before(given) && key.after(closest)){
				closest = key;
			}
		}
		return closest;
	}




	public void updatePriceTo(Money amount) {
		@SuppressWarnings("deprecation")
		Date today = DateTime.now().toDateMidnight().toDate();
		this.getHistoricalRecord().put(today, amount);
	}
	

}
